<template>
  <div class="goods-management">
    <div class="search-bar">
      <el-input 
        v-model="searchForm.searchText" 
        placeholder="商品名称" 
        style="width: 200px; margin-right: 10px" 
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="goToAddPage">新增</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 1300px">
      <el-table-column prop="id" label="商品ID" width="80" align="center" />
      <el-table-column prop="name" label="商品名称" min-width="120" />
      <el-table-column label="商品图片" width="120">
        <template #default="{ row }">
          <el-image
            :src="'http://localhost:9191' + row.imgs"
            :preview-src-list="['http://localhost:9191' + row.imgs]"
            fit="cover"
            style="width: 50px; height: 50px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="description" label="商品描述" min-width="150" show-overflow-tooltip />
      <el-table-column prop="discount" label="折扣" width="80" align="center" />
      <el-table-column prop="sales" label="销量" width="80" align="center" />
      <el-table-column prop="saleMoney" label="销售额(元)" width="120" align="center" />
      <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
      <el-table-column label="推荐" width="80" align="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.recommend"
            @change="handleRecommendChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template #default="{ row }">
          <el-button type="text" @click="showEditDialog(row)">修改</el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <span>共{{ total }}条</span>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '@/utils/request'

const router = useRouter()
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)

const searchForm = reactive({
  searchText: ''
})

const getGoodsList = async () => {
  loading.value = true
  try {
    const res = await request({
      url: 'http://localhost:9191/api/good/fullPage?page',
      method: 'get',
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        searchText: searchForm.searchText
      }
    })
    tableData.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  getGoodsList()
}

const resetSearch = () => {
  searchForm.searchText = ''
  handleSearch()
}

const goToAddPage = () => {
  router.push('/admin/index/tian')
}

const showEditDialog = (row) => {
  // 这里可以改为跳转到编辑页面，或者保留对话框编辑方式
  // 根据你的需求决定
  router.push(`/admin/index/edit/${row.id}`)
}

const handleRecommendChange = async (row) => {
  try {
    await request({
      url: '/api/good/recommend',
      method: 'get',
      params: {
        id: row.id,
        isRecommend: row.recommend
      }
    })
    ElMessage.success('操作成功')
  } catch (error) {
    console.error('修改推荐状态失败:', error)
    row.recommend = !row.recommend
    ElMessage.error('操作失败')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该商品吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request({
        url: `/api/good/${row.id}`,
        method: 'delete'
      })
      ElMessage.success('删除成功')
      getGoodsList()
    } catch (error) {
      console.error('删除商品失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getGoodsList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getGoodsList()
}

onMounted(() => {
  getGoodsList()
})
</script>

<style scoped>
.goods-management {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>